//
//  FCRelationTypeManagerChoiceViewController.m
//  customerRelation
//
//  Created by 陈文斌 on 2019/6/20.
//

#import "FCRelationTypeManagerChoiceViewController.h"
#import "CustomerRelationHeader.h"
#import "FCCustomerRelationRequest.h"
#import "FCEmployeeGroupView.h"
#import "FCWorkGroupListModel.h"
#import "UIImageView+WebCache.h"
#import "FCRelationTypeManagerCell.h"
#import "UIViewController+returnBlock.h"

#define WorkGroupKey @"workGroup"
#define EmployeesKey @"employees"
@interface FCRelationTypeManagerChoiceViewController ()
<
UITableViewDelegate,
UITableViewDataSource
>

@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UIButton *searchBtn;
@property (nonatomic, strong) UITableView *tableView;

// 部门列表
@property (nonatomic, strong) NSMutableArray<FCCompanyDepartmentModel *> *departmentList;
@property (nonatomic, strong) NSMutableArray *groupViewArr;

@property (nonatomic, strong) NSMutableDictionary *employeeDic;
@property (nonatomic, strong) NSMutableArray *employeeArr;

@property (nonatomic, assign) int skip;

@end

@implementation FCRelationTypeManagerChoiceViewController
- (NSMutableDictionary *)employeeDic{
    if (!_employeeDic) {
        _employeeDic = [NSMutableDictionary dictionary];
    }
    return _employeeDic;
}
- (NSMutableArray *)employeeArr{
    if (!_employeeArr) {
        _employeeArr = [NSMutableArray array];
    }
    return _employeeArr;
}
- (NSMutableArray *)departmentList{
    if (!_departmentList) {
        _departmentList = [NSMutableArray array];
    }
    return _departmentList;
}
- (NSMutableArray *)groupViewArr{
    if (!_groupViewArr) {
        _groupViewArr = [NSMutableArray array];
    }
    return _groupViewArr;
}

- (void)setupUI{
    if (self.title.length == 0) {
        self.title = @"选择授权负责人";
    }
    
    self.view.backgroundColor = FCBackColor;
    
    self.searchView = [[UIView alloc] init];
    [self.view addSubview:_searchView];
    [_searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.left.and.right.mas_equalTo(0);
        make.height.mas_equalTo(48);
    }];
    _searchView.backgroundColor = [UIColor whiteColor];
    _searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_searchView addSubview:_searchBtn];
    [_searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(5);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(30);
    }];
    _searchBtn.titleLabel.font = font13;
    _searchBtn.backgroundColor = FCBackColor;
    _searchBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    _searchBtn.layer.cornerRadius = 4;
    _searchBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [_searchBtn setImage:customerRelationImageName(@"nav_ic_search_g") forState:UIControlStateNormal];
//    [_searchBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 12, 0, 0)];
    [_searchBtn setTitle:customerRelationLocaChanged(@"global_general_search", @"搜索") forState:UIControlStateNormal];
    [_searchBtn setTitleColor:FCGrayTxtPlaceColor forState:UIControlStateNormal];
//    [_searchBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 18, 0, 0)];
    [_searchBtn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark - 搜索
- (void)searchAction{
    XMGLog(@"搜索");
    WJCWeakSelf
    UIViewController *vc = [self pushAppControllerWithControllerName:@"FCCSearchViewController" andObjectData:@{@"isSearchColleague": @(YES)} andTitle:nil];
    vc.idBlock = ^(id object) {
        [self.navigationController popViewControllerAnimated:YES];
        weakSelf.idBlock(object);
    };
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupTableView];
    [self getDepartment];
}

- (void)setupTableView{
    self.tableView = [UITableView new];
    [self.view addSubview:self.tableView];
    WJCWeakSelf
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.searchView.mas_bottom).mas_equalTo(8);
        make.left.and.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-FCTabbarSafeBottomMargin);
    }];
    self.tableView.backgroundColor = FCBackColor;
    self.tableView.separatorStyle = UITableViewCellEditingStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self setExtraCellLineHidden:self.tableView];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
}

- (void)setExtraCellLineHidden: (UITableView *)tableView{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor whiteColor];
    [tableView setTableFooterView:view];
}

#pragma mark - tableView Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.departmentList.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 48;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    FCEmployeeGroupView *groupView;
    
    if (self.groupViewArr.count > section) {
        groupView = self.groupViewArr[section];
    } else {
        groupView = [[FCEmployeeGroupView alloc] init];
        [self.groupViewArr addObject:groupView];
    }
    groupView.tag = section;
    [groupView addTarget:self action:@selector(changeExpandStatus:) forControlEvents:UIControlEventTouchUpInside];
    FCCompanyDepartmentModel *department = self.departmentList[section];
    groupView.groupNameLabel.text = department.Name ?: @"";
    groupView.employeeCountLabel.text = department.Counts;
    
    return groupView;
}
// 头部箭头动画
- (void)changeExpandStatus:(FCEmployeeGroupView *)sender{
    
    sender.isExpand = !sender.isExpand;
    
    if (sender.isExpand) {
        CGAffineTransform transform = CGAffineTransformMakeRotation(90 * M_PI/180.0);
        [sender.arrowImageView setTransform:transform];
        
    } else {
        CGAffineTransform transform = CGAffineTransformMakeRotation(0 * M_PI/180.0);
        [sender.arrowImageView setTransform:transform];
    }
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    FCEmployeeGroupView *employeeGroupView = self.groupViewArr[section];
    NSArray *employees = self.departmentList[section].Employees;
    
    if (employeeGroupView.isExpand) {
        return employees.count;
    } else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 56;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FCEmployeeModel *employee = self.departmentList[indexPath.section].Employees[indexPath.row];
    
    FCRelationTypeManagerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (!cell) {
        cell = [[FCRelationTypeManagerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    [cell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:employee.PortraitUrl] placeholderImage:headPlaceImage];
    cell.employeeNameLabel.text = employee.Name ?: @"";
    if (employee.CompanyBrandName && employee.JobTitle) {
        cell.employeeDetailLabel.text = [NSString stringWithFormat:@"%@-%@",employee.CompanyBrandName ?: @"",employee.JobTitle ?: @""];
    } else{
        cell.employeeDetailLabel.text = [NSString stringWithFormat:@"%@%@",employee.CompanyBrandName ?: @"",employee.JobTitle ?: @""];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FCEmployeeModel *employee = self.departmentList[indexPath.section].Employees[indexPath.row];
    if (self.idBlock) {
        [self.navigationController popViewControllerAnimated:YES];
        self.idBlock(employee);
    }
}

#pragma mark - 获取数据
- (void)getDepartment{
    //获取缓存数据
    self.departmentList=nil;
    
    NSMutableArray *arr=[saveSandBox getDataBaseWithClass:[FCCompanyDepartmentModel class] andLimitType:nil];
    if (arr.count>0) {
        self.departmentList = arr;
        [self.tableView reloadData];
        return;
    }
    [self getMyDepartmentList];
}
/**
 企业部门列表
 */
- (void)getMyDepartmentList {
    if (![FCEmployeeModel isLoginWithNotice:NO]) return;
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    WJCWeakSelf
    [FCCustomerRelationRequest getCompanyCompanydepartmentsWithCompanyId:[FCEmployeeModel getMinieCompanyId] orOtherParam:nil success:^(NSArray<FCCompanyDepartmentModel *> * _Nonnull result) {
        self.departmentList = [result mutableCopy];
        
        [self getMyEmployeesList:@"0"];
        if (self.tableView) {
            [SVProgressHUD dismiss];
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
            [weakSelf.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

/**
 企业的职员列表
 */
- (void)getMyEmployeesList:(NSString *)skip{
    WJCWeakSelf
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"CompanyId"] = [FCEmployeeModel getMinieCompanyId];
    param[@"skip"] = skip;
    param[@"take"] = @15;
    param[@"meId"] = [FCEmployeeModel getMinieEmpId];
    
    [FCCustomerRelationRequest myEmployeesListWithParam:param success:^(NSMutableArray <FCEmployeeModel *> *employees) {
        
        for (FCCompanyDepartmentModel *department in self.departmentList) {
            if (!department.Employees) {
                department.Employees = [NSMutableArray array];
            }
            for (FCEmployeeModel *emp in employees) {
                if ([department.Id isEqualToString:emp.CompanyDepartmentId]) {
                    [department.Employees addObject:emp];
                    continue;
                }
            }
        }
        [weakSelf.tableView reloadData];
        
        if (employees.count > 0) {
            [self getMyEmployeesList:[NSString stringWithFormat:@"%lu",[skip integerValue] + employees.count]]; //加载下一页
            
        } else {
//            [WJCSaveFile saveFileInDocumentFileWithObject:self.departGroupArray andName:@"empDepartment"];
        }
        
    } failure:^(NSError *error) {
        
    }];
}

@end
